<?php 
	require_once '../function.php';

	$user = xiu_get_current_user_admin();


	// 获取分类信息
	$categories = xiu_fetch_db_all("select * from categories where user_id = {$user['id']};");

	// 保存文章
	// ====================================================================================
	function post_save(){
		var_dump($_POST);
		global $user;

		if (empty($_POST['title'])) {
			$GLOBALS['message'] = '请输入标题';
			return;
		}

		if (empty($_POST['content'])) {
			$GLOBALS['message'] = '请输入文章内容';
			return;
		}

		if (empty($_POST['slug'])) {
			$GLOBALS['message'] = '请输入文章别名';
			return;
		}

		// if (!isset($_FILES['pic'])) {
		// 	$GLOBALS['message'] = '请选择图片1';
		// 	return;
		// }

		if (empty($_POST['category'])) {
			$GLOBALS['message'] = '请选择分类';
			return;
		}

		if (empty($_POST['status'])) {
			$GLOBALS['message'] = '请选择状态';
			return;
		}

		// if (empty($_POST['html'])) {
		// 	$GLOBALS['message'] = '请输入文章内容';
		// 	return;
		// }

		$title = $_POST['title'];
		$content = $_POST['content'];
		$slug = $_POST['slug'];
		$pic = $_FILES['pic'];
		$created = $_POST['created'];
		$category = $_POST['category'];
		$status = $_POST['status'];
		$html = $_POST['html'];

		// 处理上传图片
		
		// array(5) {
		//   ["name"]=>
		//   string(10) "avatar.jpg"
		//   ["type"]=>
		//   string(10) "image/jpeg"
		//   ["tmp_name"]=>
		//   string(27) "C:\Windows\Temp\php77DF.tmp"
		//   ["error"]=>
		//   int(0)
		//   ["size"]=>
		//   int(25656)
		// }
		if ($pic['size'] === 0) {
			$GLOBALS['message'] = '请选择图片';
			return;
		}

		
		// 验证图片的后缀名
		$suffix_arr = array('jpg', 'jpeg', 'png');
		// 获取文件后缀名
		$file_suffix = explode('.', $pic['name'])[1];
		if (!in_array($file_suffix, $suffix_arr)) {
			$GLOBALS['message'] = '仅支持jpg,jpeg,png格式的图片';
			return;
		}

		// 验证图片的MIMETYPE
		$mimetype_array = array('image/jpg', 'image/jpeg', 'image/png');
		if (!in_array($pic['type'], $mimetype_array)) {
			$GLOBALS['message'] = '仅支持jpg,jpeg,png格式的图片';
			return;
		}

		if ($pic['error'] !== UPLOAD_ERR_OK) {
			$GLOBALS['message'] = "上传失败！";
			return;
		}

		// 移动文件需要使用相对路径
		if (!is_dir('../static/uploads/post-pic')) {
			mkdir('../static/uploads/post-pic');
		}
		
		$file_name = $pic['tmp_name'];
		$target = '../static/uploads/post-pic/'.uniqid().$pic['name'];

		//将文件从临时文件夹移动至网站目录
		$moved = move_uploaded_file($file_name, $target);
		if (!$moved) {
			$GLOBALS['message'] = '文件上传失败！';
			return;
		}

		// 文件上传成功
		$affect_rows = xiu_operation_db("insert into posts values(null,'{$slug}','{$title}','{$content}','{$created}','{$target}',0,0,{$status},{$user['id']},{$category},'{$html}')");

		if ($affect_rows <= 0) {
			$GLOBALS['message'] = '上传文章失败';
			return;
		}

		header('Location: /admin/posts.php');
	}

	//修改文章
	// ====================================================================================
	function post_modify(){
		global $m_post;


		$title = empty($_POST['title']) ? $m_post['title'] : $_POST['title'];
		$content = empty($_POST['content']) ? $m_post['content'] : $_POST['content'];
		$slug = empty($_POST['slug']) ? $m_post['slug'] : $_POST['slug'];
		$category = empty($_POST['category']) ? $m_post['category'] : $_POST['category'];
		$created = $_POST['created'];
		$status = $_POST['status'];
		$views = $m_post['views'];
		$likes = $m_post['likes'];
		$status = $_POST['status'];
		$user_id = $m_post['user_id'];
		$category_id = $_POST['category'];
		$html = $_POST['html'];

		if ($_FILES['pic']['size'] === 0) {
			$target = $m_post['feature'];
		}else{
			$pic = $_FILES['pic'];
			// 验证图片的后缀名
			$suffix_arr = array('jpg', 'jpeg', 'png');
			// 获取文件后缀名
			$file_suffix = explode('.', $pic['name'])[1];
			if (!in_array($file_suffix, $suffix_arr)) {
				$GLOBALS['message'] = '仅支持jpg,jpeg,png格式的图片';
				return;
			}

			// 验证图片的MIMETYPE
			$mimetype_array = array('image/jpg', 'image/jpeg', 'image/png');
			if (!in_array($pic['type'], $mimetype_array)) {
				$GLOBALS['message'] = '仅支持jpg,jpeg,png格式的图片';
				return;
			}

			if ($pic['error'] !== UPLOAD_ERR_OK) {
				$GLOBALS['message'] = "上传失败！";
				return;
			}

			// 移动文件需要使用相对路径
			if (!is_dir('../static/uploads/post-pic')) {
				mkdir('../static/uploads/post-pic');
			}
			
			$file_name = $pic['tmp_name'];
			$target = '../static/uploads/post-pic/'.uniqid().$pic['name'];

			//将文件从临时文件夹移动至网站目录
			$moved = move_uploaded_file($file_name, $target);
			if (!$moved) {
				$GLOBALS['message'] = '文件上传失败！';
				return;
			}
		}

		// 文件上传成功
		$affect_rows = xiu_operation_db("update posts set id={$m_post['id']},slug='{$slug}',title='{$title}',content='{$content}',created='{$created}',feature='{$target}',views={$views},likes={$likes},status={$status},user_id={$user_id},category_id={$category_id},html='{$html}' where id = {$m_post['id']};");

		if ($affect_rows <= 0) {
			$GLOBALS['message'] = '上传文章失败';
			return;
		}

		header('Location: /admin/posts.php');


	}

	// 判断是否有id
	// ====================================================================================
	if (!empty($_GET['id'])) {
		$id = (int)$_GET['id'];
		if (!is_int($id)) {
			exit('<h1>参数不正确<h1>');
		}

		// 获取要修改的文章内容
		$m_post = xiu_fetch_db_one("select * from posts where id = {$id}");
	}

	// 判断提交方式
	// ====================================================================================
	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
		// 新增文章
		if (empty($_GET['id'])) {
			post_save(); 
		}else{
			post_modify();
		}
	}



 ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>写文章</title>
	<link rel="stylesheet" type="text/css" href="/static/vendors/bootstrap4.6/css/bootstrap.css">
	<link rel="stylesheet" type="text/css" href="/static/css/admin.css">
	<!-- vditor -->
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vditor/dist/index.css" />
	<script src="https://cdn.jsdelivr.net/npm/vditor/dist/index.min.js"></script>

</head>
<body>
	<div class="main">
		<?php include './inc/navbar.php' ?>
		<div class="container-fluid">
			<div class="page-title">
				<h1>写文章</h1>
			</div>
			<?php if (isset($message)): ?>
				<div class="alert alert-danger"><?php echo $message; ?></div>
			<?php endif ?>
			<form id="formId" class="row" action="<?php echo $_SERVER['PHP_SELF'] ?><?php echo isset($m_post['id'])? '?id='.$m_post['id'] : ''; ?>" method="post" enctype="multipart/form-data">
				<div class="col-md-9">
					<div class="form-group">
						<label for="title">标题</label>
						<input type="text" name="title" id="title" class="form-control input-lg" placeholder="文章标题" autocomplete="off" value="<?php echo isset($m_post['title']) ? $m_post['title'] : (empty($_POST['title']) ? '': $_POST['title']); ?>">
					</div>
					<div class="form-group">
						<label for="fieldTest">内容</label>
						<div id="vditor" class="vditor"></div>
						<input type="hidden" name="content" class="content" value="<?php echo isset($m_post['content'])? $m_post['content'] : ''; ?>">
						<input type="hidden" name="html" class="html">
					</div>

				</div>
				<div class="col-md-3">
					<div class="form-group">
						<label for="slug">别名</label>
						<input type="text" name="slug" id="slug" class="form-control" placeholder="slug" autocomplete="off" value="<?php echo isset($m_post['slug']) ? $m_post['slug'] : (empty($_POST['slug']) ? '': $_POST['slug']); ?>">
					</div>
					<div class="form-group">
						<label for="pic">图像</label>
						<input type="file" name="pic" id="pic" class="form-control" placeholder="picture" accept="image/*">
					</div>
					<div class="form-group">
						<label for="category">分类</label>
						<select id="category" name="category" class="form-control">
							<?php if ($categories): ?>
								<?php foreach ($categories as $item): ?>
									<option value="<?php echo $item['id'] ?>" <?php echo isset($m_post['category_id'])&&$m_post['category_id'] == $item['id'] ? 'selected' : ''; ?>><?php echo $item['name'] ?></option>
								<?php endforeach ?>
							<?php endif ?>
							<?php if (!$categories): ?>
								<option>请先建立分类</option>
							<?php endif ?>
							
						</select>
					</div>
					<div class="form-group">
						<label for="created">发布时间</label>
						<input type="datetime-local" name="created" id="created" class="form-control" readonly="readonly">
					</div>
					<div class="form-group">
						<label for="staus">状态</label>
						<select id="staus" name="status" class="form-control">
							<option value="1" <?php echo isset($m_post['status'])&&$m_post['status'] == '1'? 'selected':''; ?>>草稿箱</option>
							<option value="2" <?php echo isset($m_post['status'])&&$m_post['status'] == '2'? 'selected':''; ?>>发布</option>
							<option value="0" <?php echo isset($m_post['status'])&&$m_post['status'] == '0'? 'selected':''; ?>>回收站</option>
						</select>
					</div>
					<div class="form-group">
						<button class="btn btn-primary" type="submit">保存</button>
					</div>
				</div>
			</form>
		</div>
	</div>
	<?php $current_page = 'post-ad' ?>
	<?php include './inc/asid.php' ?>
	<script src="/static/vendors/jQuery.js"></script>
	<script src="/static/vendors/bootstrap4.6/js/bootstrap.js"></script>
	<script src="/static/vendors/moment.js"></script>>
	<script>
		 $(function() {
		 	const vditor = new Vditor('vditor', {
		        "height": 660,
		        "theme": "#bbb",
		        "cache": {
		            "enable": false
		        },
		        "preview": {
		            "theme": {
		                "current": "light"
		            },
		            "hljs": {
		            	"enable": true,
		            	"lineNumber": true
		            }
		        },
		        "outline": {
		        	"enable": true
		        }
		    })
		 	
		 	//格式化时间
		 	function time(){
		 		setInterval(function(){
		 			$('#created').val(moment().format('YYYY-MM-DDTHH:mm'));
		 		},1000);
		 	}

		 	time();

		 	// 将编辑器中的内容赋值给input，方便post提交
		 	$('.btn').on('click', function(){ 	
		 		$('.content').val(vditor.getValue());
		 		$('.html').val(vditor.getHTML());
		 	});



		 	//给vditor赋值
		 	setTimeout(function(){
		 		var content = $('.content').val();
		 		vditor.setValue(content);
		 	}, 90);

        });
	</script>
</body>
</html>